package com.baomidou.ant.service.impl;

import com.baomidou.ant.entity.*;
import com.baomidou.ant.mapper.ReportOrderMapper;
import com.baomidou.ant.service.*;
import com.baomidou.ant.utils.MyDateUtil;
import com.baomidou.ant.utils.MyStringUtil;
import com.baomidou.ant.utils.TemplateExcelUtils;
import com.baomidou.ant.vo.request.*;
import com.baomidou.ant.vo.response.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.*;

@Service
public class ReportOrderServiceImpl extends ServiceImpl<ReportOrderMapper, ReportOrder> implements IReportOrderService {
    @Autowired
    private IWorkOrderService workOrderService;
    @Autowired
    private IProcessInfoService processInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IParentOrderService parentOrderService;
    @Value("${file.reportInfoPath}")
    private String reportInfoPath;
    @Autowired
    private IPinLibraryService pinLibraryService;
    @Autowired
    private IDeleteInfoService deleteInfoService;
    @Autowired
    private ISysDeptService deptService;


    @Override
    public boolean reportOrder(RequestReportOrderVo requestReportOrderVo){
        //上报的工序
        WorkOrder workOrder=workOrderService.queryByOrderNum(requestReportOrderVo.getOrderNum());
        //判断该工序是否上报过
        if(isNotReportedThis(requestReportOrderVo.getOrderNum(),workOrder.getNowProcess())){//没有上报过
            //判断是否完结
            if(Objects.equals(requestReportOrderVo.getOverStatus(), "1")){//选择直接完结
                //保存上报记录
                ReportOrder reportOrder=new ReportOrder();
                BeanUtils.copyProperties(requestReportOrderVo,reportOrder);
                //记录部门和状态
                reportOrder.setDeptId(workOrder.getOrderDept());
                reportOrder.setOver(true);
                //品名写入
                reportOrder.setPinId(workOrder.getPinId());
                //成功保存,处理工单信息
                if(save(reportOrder)){
                    //改变工单
                    int[] processIds= MyStringUtil.toInt(workOrder.getProcess());
                    int k=0;//计数器
                    for(int i:processIds){
                        //ProcessInfo processInfo=processInfoService.getById(i);
                        k++;
                        //到了当前工序,且当前工序是最后一到工序,没有下道工序
                        if(Objects.equals(workOrder.getNowProcess(), i) && k==processIds.length){
                            //完成了当前工序
                            reportOrder.setReportProcess(i);
                            workOrder.setOrderStatus("2");//完成
                            workOrder.setPastProcess(i);
                            workOrder.setNextProcess(0);
                            workOrder.setNowProcess(0);
                            workOrder.setNowWorker("无(已经完工)");
                            workOrder.setWorkerNo("0");
                            workOrder.setOverProcess(MyStringUtil.intToString(i,workOrder.getOverProcess()));
                            break;
                        }else if(Objects.equals(workOrder.getNowProcess(), i)){
                            //当前工序，但不是最后一道工序,有下道工序
                            //完成了当前工序,当前工序变成上道工序
                            reportOrder.setReportProcess(i);
                            workOrder.setPastProcess(i);
                            //ProcessInfo nowP=processInfoService.getById(processIds[k]);
                            //下道工序变成当前工序
                            workOrder.setNowProcess(processIds[k]);
                            //判断是否有下下道工序
                            if(k+2>processIds.length){//若没有
                                workOrder.setNextProcess(0);
                            }else {//有，下下道工序变成下道工序
                                workOrder.setNextProcess(processIds[k+1]);
                            }
                            workOrder.setOverProcess(MyStringUtil.intToString(i,workOrder.getOverProcess()));
                            //人员更新
                            String[] workerList=workOrder.getAllWorkers().split(";");
                            //如果是未事先指派工作人员
                            if(workerList.length==0){
                                workOrder.setNowWorker("上报人自选");
                            }else {
                                workOrder.setWorkerNo(workerList[k]);
                                //如果下道工序是多人进行的
                                if(ObjectUtils.isEmpty(workerList[k])){//如果仅这条未指派
                                    workOrder.setNowWorker("上报人自选");
                                }else {
                                    if (workerList[k].contains(",")) {
                                        String[] workers = workerList[k].split(",");
                                        String[] nowWorkerNameList = new String[workers.length];
                                        for (int m = 0; m < workers.length; m++) {
                                            nowWorkerNameList[m] = userService.queryByLoginName(workers[m]).getUserName();
                                        }
                                        String nowWorker = MyStringUtil.strToString(nowWorkerNameList);
                                        workOrder.setNowWorker(nowWorker);
                                    } else {
                                        SysUser worker = userService.queryByLoginName(workerList[k]);
                                        workOrder.setNowWorker(worker.getUserName());
                                    }
                                }
                            }
                            break;
                        }
                    }
                    //当前工序流入时间设置
                    workOrder.setCreateNow(LocalDateTime.now());
                    //自动检录
                    workOrder.setCheck(true);
                    //当前数量设置
                    workOrder.setAmount(reportOrder.getReportAmount()+requestReportOrderVo.getSupplyAmount());
                    workOrder.setSupplyAmount(workOrder.getSupplyAmount()+requestReportOrderVo.getSupplyAmount());
                    //补录数量冲抵不良数
                    if(workOrder.getPastProcess()==0){//说明这是第一道工序
                        workOrder.setBadAmount(requestReportOrderVo.getBadAmount()-requestReportOrderVo.getSupplyAmount());
                    }else//非第一道工序，叠加不良数
                        workOrder.setBadAmount(workOrder.getBadAmount()+requestReportOrderVo.getBadAmount()-requestReportOrderVo.getSupplyAmount());
                    //保存
                    updateById(reportOrder);
                    workOrderService.updateById(workOrder);
                    //纳入父工单
                    parentOrderService.addAmount(workOrder);
                    return true;
                }else
                    return false;
            }else{
                ReportOrder reportOrder=new ReportOrder();//创建新的一条上报记录
                BeanUtils.copyProperties(requestReportOrderVo,reportOrder);
                reportOrder.setReportProcess(workOrder.getNowProcess());
                reportOrder.setDeptId(workOrder.getOrderDept());
                //品名写入
                reportOrder.setPinId(workOrder.getPinId());
                //因为这次没完工则不需要改变工单状态,只需要计数
                workOrder.setSupplyAmount(workOrder.getSupplyAmount()+requestReportOrderVo.getSupplyAmount());
//                workOrder.setAmount(requestReportOrderVo.getReportAmount());
                workOrderService.updateById(workOrder);
                return save(reportOrder);
            }
        }else{//上报过该工序
            //得到这道工序所有的上报记录
            List<ReportOrder> reportOrderList=queryAllReported(requestReportOrderVo.getOrderNum(),workOrder.getNowProcess());
            //获得当前上报人那条记录
            ReportOrder reportOrder=new ReportOrder();
            for(ReportOrder order:reportOrderList){
                if(Objects.equals(order.getWorkerNo(), requestReportOrderVo.getWorkerNo())){
                    //除了不良数
                    //int badAmount=order.getBadAmount();
                    BeanUtils.copyProperties(order,reportOrder);
                    //reportOrder.setBadAmount(badAmount);
                    break;
                }
            }
            //判断是否为空,为空代表当前上报人没有上报过这道工序
            if(ObjectUtils.isEmpty(reportOrder.getOrderNum())){
                //新增一条属于当前上报人的上报记录人
                BeanUtils.copyProperties(requestReportOrderVo,reportOrder);
                //初始化上报数量
                reportOrder.setReportAmount(0);
                reportOrder.setBadAmount(0);
                reportOrder.setDeptId(workOrder.getOrderDept());
                //品名写入
                reportOrder.setPinId(workOrder.getPinId());
                //保存更改
                saveOrUpdate(reportOrder);
            }
            if(Objects.equals(requestReportOrderVo.getOverStatus(), "1")){//选择完工
                //完工，之前不属于当前上报人的上报记录也需要刷新状态
                for(ReportOrder re:reportOrderList){
                    re.setOver(true);
                    updateById(re);
                }
                //改变上报记录----状态和上报数量改变
                reportOrder.setOver(true);
                reportOrder.setReportAmount(reportOrder.getReportAmount()+requestReportOrderVo.getReportAmount());
                reportOrder.setBadAmount(reportOrder.getBadAmount()+requestReportOrderVo.getBadAmount());
                reportOrder.setSupplyAmount(reportOrder.getSupplyAmount()+requestReportOrderVo.getSupplyAmount());
                saveOrUpdate(reportOrder);
                //改变工单记录
                int[] processIds= MyStringUtil.toInt(workOrder.getProcess());
                int k=0;//计数器
                for(int i:processIds){
                    //ProcessInfo processInfo=processInfoService.getById(i);
                    k++;
                    //到了当前工序,且当前工序是最后一到工序,没有下道工序
                    if(Objects.equals(workOrder.getNowProcess(), i) && k==processIds.length){
                        //完成了当前工序
                        reportOrder.setReportProcess(i);
                        workOrder.setOrderStatus("2");//完成
                        workOrder.setPastProcess(i);
                        workOrder.setNextProcess(0);
                        workOrder.setNowProcess(0);
                        workOrder.setNowWorker("无(已经完工)");
                        workOrder.setWorkerNo("0");
                        workOrder.setOverProcess(MyStringUtil.intToString(i,workOrder.getOverProcess()));break;
                    }else if(Objects.equals(workOrder.getNowProcess(), i)){
                        //当前工序，但不是最后一道工序,有下道工序
                        //完成了当前工序,当前工序变成上道工序
                        reportOrder.setReportProcess(i);
                        workOrder.setPastProcess(i);
                        //ProcessInfo nowP=processInfoService.getById(processIds[k]);
                        //下道工序变成当前工序
                        workOrder.setNowProcess(processIds[k]);
                        //判断是否有下下道工序
                        if(k+2>processIds.length){//若没有
                            workOrder.setNextProcess(0);
                        }else {//有，下下道工序变成下道工序
                            ProcessInfo nextP=processInfoService.getById(processIds[k+1]);
                            workOrder.setNextProcess(processIds[k+1]);
                        }
                        workOrder.setOverProcess(MyStringUtil.intToString(i,workOrder.getOverProcess()));
                        //人员更新
                        String[] workerList=workOrder.getAllWorkers().split(";");
                        if(workerList.length==0){
                            workOrder.setNowWorker("上报人自选");
                        }else {
                            workOrder.setWorkerNo(workerList[k]);
                            //如果下道工序是多人进行的
                            if(ObjectUtils.isEmpty(workerList[k])){
                                workOrder.setNowWorker("上报人自选");
                            }else {
                                if (workerList[k].contains(",")) {
                                    String[] workers = workerList[k].split(",");
                                    String[] nowWorkerNameList = new String[workers.length];
                                    for (int m = 0; m < workers.length; m++) {
                                        nowWorkerNameList[m] = userService.queryByLoginName(workers[m]).getUserName();
                                    }
                                    String nowWorker = MyStringUtil.strToString(nowWorkerNameList);
                                    workOrder.setNowWorker(nowWorker);
                                } else {
                                    SysUser worker = userService.queryByLoginName(workerList[k]);
                                    workOrder.setNowWorker(worker.getUserName());
                                }
                            }
                        }
                        break;
                    }
                }
                workOrder.setCreateNow(LocalDateTime.now());
                workOrder.setCheck(true);
                //当前数量设置
                workOrder.setSupplyAmount(workOrder.getSupplyAmount()+requestReportOrderVo.getSupplyAmount());
                int amount=requestReportOrderVo.getReportAmount();
                int supplyAmount=requestReportOrderVo.getSupplyAmount();
                for(ReportOrder order:reportOrderList){
                    amount+=order.getReportAmount();
                    supplyAmount+=order.getSupplyAmount();
                }
                //加上补录的余数
                workOrder.setAmount(amount+supplyAmount);
                //不良数要叠加记录
                int badAmount=requestReportOrderVo.getBadAmount();
                for(ReportOrder order:reportOrderList){
                    badAmount+=order.getBadAmount();
                }
                //补录数量冲抵不良数
                workOrder.setBadAmount(workOrder.getBadAmount()+badAmount-supplyAmount);
                //保存
                updateById(reportOrder);
                workOrderService.updateById(workOrder);
                //纳入父工单
                parentOrderService.addAmount(workOrder);
                return true;
            }else{
                //只改变上报记录，不改变工单，工单继续维持
                reportOrder.setOver(false);
                reportOrder.setReportProcess(workOrder.getNowProcess());
                reportOrder.setReportAmount(reportOrder.getReportAmount()+requestReportOrderVo.getReportAmount());
                reportOrder.setBadAmount(reportOrder.getBadAmount()+requestReportOrderVo.getBadAmount());
                //品名写入
                reportOrder.setPinId(workOrder.getPinId());
                //因为这次没完工则不需要改变工单状态,只需要计数
                workOrder.setSupplyAmount(workOrder.getSupplyAmount()+requestReportOrderVo.getSupplyAmount());
                workOrderService.updateById(workOrder);
                return updateById(reportOrder);
            }
        }
    }

    @Override
    public boolean checkAmount(RequestReportOrderVo requestReportOrderVo) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(requestReportOrderVo.getOrderNum());
        int totalAmount;
        //如果没上报过该工序
        if(isNotReportedThis(requestReportOrderVo.getOrderNum(),workOrder.getNowProcess())){
            //上报总数(良品和不良品总计)
            totalAmount=requestReportOrderVo.getReportAmount()+requestReportOrderVo.getBadAmount();
        }else {
            List<ReportOrder> reportOrderList= queryAllReported(requestReportOrderVo.getOrderNum(),workOrder.getNowProcess());
            int reportAmount=0;
            for(ReportOrder order:reportOrderList){
                reportAmount=reportAmount+order.getBadAmount()+order.getReportAmount();
            }
            //上报总数则等于上次上报加这次上报
            totalAmount=requestReportOrderVo.getReportAmount()+requestReportOrderVo.getBadAmount()+reportAmount;
        }
        //没有上报记录,只需要对比计划数
        if(isReported(requestReportOrderVo.getOrderNum())){
            //是否超出计划数量
            return totalAmount <= workOrder.getAmountPlan();
        }
        //是否超出当前数量
        return totalAmount<=workOrder.getAmount();
    }

    @Override
    public boolean checkSupply(RequestReportOrderVo requestReportOrderVo) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(requestReportOrderVo.getOrderNum());
        int[] ids=MyStringUtil.toInt(workOrder.getProcess());
        return workOrder.getNowProcess() == ids[ids.length - 1] || requestReportOrderVo.getSupplyAmount() <= 0;
    }

    @Override
    public boolean checkWorker(RequestReportOrderVo requestReportOrderVo) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(requestReportOrderVo.getOrderNum());
        String[] workerNos=workOrder.getWorkerNo().split(",");
        boolean result=false;//计数器
        for(String workerNo:workerNos){
            if (Objects.equals(workerNo, requestReportOrderVo.getWorkerNo())) {
                result = true;
                break;
            }
        }
        return result;
    }

    @Override
    public boolean isReported(String orderNum) {
        //得到所有上报记录
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum);
        queryWrapper.eq("is_over","1");
        List<ReportOrder> reportList=list(queryWrapper);
        //上报记录
        return reportList == null || reportList.size() == 0;
    }

    @Override
    public boolean isNotReportedThis(String orderNum, Integer processId) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(orderNum);
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum);
        //queryWrapper.eq("worker_no",workerNo);
        queryWrapper.eq("report_process",workOrder.getNowProcess());
        queryWrapper.eq("is_over","0");
        List<ReportOrder> reportList=list(queryWrapper);
        return reportList == null || reportList.size() == 0;
    }

    @Override
    public ResponseListNumVo getNum(String orderNum) {
        WorkOrder workOrder=workOrderService.queryByOrderNum(orderNum);
//        int badTotalAmount=0;
        int missingAmount=workOrder.getAmountPlan()-workOrder.getAmount()-workOrder.getBadAmount()-workOrder.getSupplyAmount();
//        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("order_num",orderNum);
//        queryWrapper.eq("is_over","1");
//        List<ReportOrder> reportOrderList=list(queryWrapper);
//        if(!(reportOrderList==null||reportOrderList.size()==0)){
//            for(int i=0;i<reportOrderList.size();i++){
//                badTotalAmount+=reportOrderList.get(i).getBadAmount();
//            }
//            for(int i=0;i<reportOrderList.size();i++){
//                missingAmount+=reportOrderList.get(i).getMissingAmount();
//            }
//        }

        ResponseListNumVo responseListNumVo=new ResponseListNumVo();
        responseListNumVo.setAmount(workOrder.getAmount());
        responseListNumVo.setAmountPlan(workOrder.getAmountPlan());
        responseListNumVo.setBadTotalAmount(workOrder.getBadAmount());
        responseListNumVo.setMissingAmount(missingAmount);
        return responseListNumVo;
    }

    @Override
    public ResponseListNumOfReportedVo getNumOfReported(RequestReportedNumVo requestReportedNumVo) {
        //得到工单
        WorkOrder workOrder=workOrderService.queryByOrderNum(requestReportedNumVo.getOrderNum());
        ResponseListNumOfReportedVo vo=new ResponseListNumOfReportedVo();
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",requestReportedNumVo.getOrderNum());
        queryWrapper.eq("report_process",workOrder.getNowProcess());
        //queryWrapper.eq("worker_no",requestReportedNumVo.getWorkerNo());
        queryWrapper.eq("is_over","0");
        List<ReportOrder> reportOrderList=list(queryWrapper);
        if(reportOrderList==null||reportOrderList.size()==0){
            vo.setAmount(0);
            vo.setBadAmount(0);
        }else {
            int amount = 0;
            int badAmount = 0;
            for (ReportOrder reportOrder : reportOrderList) {
                //补录余数也要记录
                amount=amount +reportOrder.getReportAmount()+reportOrder.getSupplyAmount();
                badAmount =badAmount+ reportOrder.getBadAmount();
            }
            vo.setAmount(amount);
            vo.setBadAmount(badAmount);
        }
        //找到最后一次上报的数量
        vo.setNowAmount(workOrder.getAmount());
        vo.setReportedSupply(workOrder.getSupplyAmount());
        return vo;
    }

    @Override
    public IPage<ResponseGetMyDoneVo> getMyDone(RequestGetMyDoneVo requestGetMyDoneVo){
        IPage<ReportOrder> iPage=new Page<>(requestGetMyDoneVo.getDisplayStart(),requestGetMyDoneVo.getDisplayLength());
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(requestGetMyDoneVo.getOrderNum())){
            queryWrapper.like("order_num",requestGetMyDoneVo.getOrderNum());
        }
        //pinId
        if(ObjectUtils.isNotEmpty(requestGetMyDoneVo.getPinId())){
            queryWrapper.eq("pin_id",requestGetMyDoneVo.getPinId());
        }
        //时间排序
        if(Objects.equals(requestGetMyDoneVo.getDesc(), "desc")|| ObjectUtils.isEmpty(requestGetMyDoneVo.getDesc())){
            queryWrapper.orderByDesc("create_time");
        }
        if(Objects.equals(requestGetMyDoneVo.getDesc(), "asc")){
            queryWrapper.orderByAsc("create_time");
        }
        //是否缺数

        //工序查询
        if(ObjectUtils.isNotEmpty(requestGetMyDoneVo.getProcess())){
            queryWrapper.eq("report_process",requestGetMyDoneVo.getProcess());
        }
        //是否完工
//        if(ObjectUtils.isNotEmpty(requestGetMyDoneVo.getReportStatus())){
//            queryWrapper.eq("is_over",requestGetMyDoneVo.getReportStatus());
//        }
        //时间范围
        if(ObjectUtils.isNotEmpty(requestGetMyDoneVo.getStartDate())){
            //按时间范围选择
            String startTime= MyDateUtil.dateCheckOfDay(requestGetMyDoneVo.getStartDate());
            String endTime= MyDateUtil.dateCheckOfDay(requestGetMyDoneVo.getEndDate());
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  >= CONVERT(varchar(30),getdate() - "+startTime+",102)");
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  <= CONVERT(varchar(30),getdate() - "+endTime+",102)");
        }
        //得到自己的已办
        SysUser user=userService.queryByLoginName(requestGetMyDoneVo.getWorkerNo());
        //非管理员只能看自己的
        if(Objects.equals(user.getType(), "2")){
            queryWrapper.eq("worker_no",user.getLoginName());
        }
        //非超级管理员只能看自己部门的
        if(Objects.equals(user.getType(), "0")){
            queryWrapper.eq("dept_id",user.getDeptId());
        }else{
            if(ObjectUtils.isNotEmpty(requestGetMyDoneVo.getDept())){
                queryWrapper.eq("dept_id",requestGetMyDoneVo.getDept());
            }
        }
        int allTotal=list(queryWrapper).size();
        //得到结果集
        IPage<ReportOrder> page=page(iPage,queryWrapper);
        return page.convert(reportOrder -> {
            ResponseGetMyDoneVo vo = new ResponseGetMyDoneVo();
            BeanUtils.copyProperties(reportOrder, vo);
            if(ObjectUtils.isNotEmpty(reportOrder.getPinId())){
                PinLibrary pin=pinLibraryService.getById(reportOrder.getPinId());
                vo.setPinName(pin.getPinName());
            }
            //未报耗材
            if (ObjectUtils.isEmpty(vo.getStuffNum())) {
                vo.setStuffNum("未报");
            }
            if (ObjectUtils.isEmpty(vo.getCoreNum())) {
                vo.setCoreNum("未报");
            }
            //得到上报工序
            if (reportOrder.getReportProcess() == null || reportOrder.getReportProcess() == 0) {
                vo.setReportProcess("值为null");
            } else
                vo.setReportProcess(processInfoService.getById(reportOrder.getReportProcess()).getProcessName());
            vo.setAllTotal(allTotal);
            return vo;
        });
    }

    @Override
    public void exportReportInfo(HttpServletResponse response, String[] data) {
        try {
            //得到数据
            QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
            if(StringUtils.isNotBlank(data[1])){
                queryWrapper.like("order_num",data[0]);
            }
            //pinId
            if(ObjectUtils.isNotEmpty(data[6])){
                queryWrapper.eq("pin_id",data[6]);
            }
            //是否缺数
//            if(ObjectUtils.isNotEmpty(vo.getMissingStatus())){
//                queryWrapper.eq("is_missing",vo.getMissingStatus());
//            }
            //工序查询
            if(ObjectUtils.isNotEmpty(data[2])){
                queryWrapper.eq("report_process",data[2]);
            }
            //是否完工
//            if(ObjectUtils.isNotEmpty(vo.getReportStatus())){
//                queryWrapper.eq("is_over",vo.getReportStatus());
//            }
            //时间范围
            if(ObjectUtils.isNotEmpty(data[4])){
                //按时间范围选择
                String startTime= MyDateUtil.dateCheckOfDay(data[4]);
                String endTime= MyDateUtil.dateCheckOfDay(data[5]);
                queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  >= CONVERT(varchar(30),getdate() - "+startTime+",102)");
                queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  <= CONVERT(varchar(30),getdate() - "+endTime+",102)");
            }
            //得到自己的已办
            SysUser user=userService.queryByLoginName(data[0]);
            //非管理员只能看自己的
            if(Objects.equals(user.getType(), "2")){
                queryWrapper.eq("worker_no",user.getLoginName());
            }
            //非超级管理员只能看自己部门的
            if(Objects.equals(user.getType(), "0")){
                queryWrapper.eq("dept_id",user.getDeptId());
            }else{
                if(ObjectUtils.isNotEmpty(data[3])){
                    queryWrapper.eq("dept_id",data[3]);
                }
            }
            List<ReportOrder> reportOrderList=list(queryWrapper);
            List<ResponseExportReportInfoVo> resultList=new ArrayList<>();
            for(ReportOrder reportOrder:reportOrderList){
                ResponseExportReportInfoVo vo=new ResponseExportReportInfoVo();
                BeanUtils.copyProperties(reportOrder,vo);
                vo.setProcessName(processInfoService.getById(reportOrder.getReportProcess()).getProcessName());
                resultList.add(vo);
            }
            String fileName=data[6]+"-"+data[2]+"-"+data[4]+"-"+data[5]+"上报记录报表";
            //数据填入
            Map<String,Object> param = new HashMap<>();
            param.put("list",resultList);
            TemplateExcelUtils.downLoadExcel(fileName,reportInfoPath,param,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int totalSize(RequestDtoVo requestDtoVo) {
        SysUser sysUser=userService.getById(requestDtoVo.getUserId());
        List<ReportOrder> reportOrderList;
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("worker_no",sysUser.getLoginName());
        reportOrderList=list(queryWrapper);
        return reportOrderList.size();
    }

    @Override
    public ResponseMyDoneInfoVo myDoneInfo(Integer reportId) {
        ReportOrder reportOrder=getById(reportId);
        ResponseMyDoneInfoVo responseMyDoneInfoVo=new ResponseMyDoneInfoVo();
        BeanUtils.copyProperties(reportOrder,responseMyDoneInfoVo);
        WorkOrder workOrder=workOrderService.queryByOrderNum(reportOrder.getOrderNum());
        responseMyDoneInfoVo.setAmountPlan(workOrder.getAmountPlan());
        //所需工序
        int[] processIds=MyStringUtil.toInt(workOrder.getProcess());
        List<String> processList=new ArrayList<>();
        for(int i:processIds){
            if(i==0){
                continue;
            }
            ProcessInfo processInfo=processInfoService.getById(i);
            processList.add(processInfo.getProcessName());
        }
        StringBuilder result= new StringBuilder();
        for(String str:processList){
            result.append(str).append(";");
        }
        responseMyDoneInfoVo.setProcess(result.toString());
        //我参与的工序
        if(reportOrder.getReportProcess()==null||reportOrder.getReportProcess()==0){
            responseMyDoneInfoVo.setReportProcess("值为null");
        }else
            responseMyDoneInfoVo.setReportProcess(processInfoService.getById(reportOrder.getReportProcess()).getProcessName());
        return responseMyDoneInfoVo;
    }

    @Override
    public List<ReportOrder> queryAllReported(String orderNum, Integer processId) {
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum).eq("report_process",processId).eq("is_over","0");
        //得到上报记录
        List<ReportOrder> reportOrderList=list(queryWrapper);
        return reportOrderList;
    }


    @Override
    public List<ReportOrder> queryByOrderNum(String orderNum) {
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",orderNum).eq("is_over","1");
        return list(queryWrapper);
    }


    @Override
    public List<ResponseListReportVo> getReport(List<ReportOrder> reportOrderList) {
        List<ResponseListReportVo> result=new ArrayList<>();
        for(ReportOrder reportOrder:reportOrderList){
            ResponseListReportVo vo=new ResponseListReportVo();
            BeanUtils.copyProperties(reportOrder,vo);
            String machineMessage=reportOrder.getMachineNum();
            vo.setMachineMessage(machineMessage);
            //上报数量含余数补录
            vo.setReportAmount(reportOrder.getReportAmount()+reportOrder.getSupplyAmount());
            //工序名获取
            if(reportOrder.getReportProcess()==null||reportOrder.getReportProcess()==0){
                vo.setReportProcess("值为null");
            }else
                vo.setReportProcess(processInfoService.getById(reportOrder.getReportProcess()).getProcessName());
            result.add(vo);
        }
        return result;
    }

    @Override
    public IPage<ResponseCheckOfStuffVo> checkStuff(RequestCheckOfStuffVo vo) {
        IPage<ReportOrder> iPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        //二合一条件
        if(ObjectUtils.isNotEmpty(vo.getCoreNum())&&ObjectUtils.isNotEmpty(vo.getStuffNum())){
            queryWrapper.and(i->i.like("core_num",vo.getCoreNum()).like("stuff_num",vo.getStuffNum()));
        }
        //单独条件
        if(ObjectUtils.isNotEmpty(vo.getCoreNum())&&ObjectUtils.isEmpty(vo.getStuffNum())){
            queryWrapper.like("core_num",vo.getCoreNum());
        }
        if(ObjectUtils.isNotEmpty(vo.getStuffNum())&&ObjectUtils.isEmpty(vo.getCoreNum())){
            queryWrapper.like("stuff_num",vo.getStuffNum());
        }
        SysUser user=userService.getById(vo.getUserId());
        //判断管理员级别
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(StringUtils.isNotBlank(vo.getDeptName())){
                queryWrapper.eq("dept_id",vo.getDeptName());
            }
        } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//只能看自己部门的
            queryWrapper.eq("dept_id",user.getDeptId());
        }
        //时间范围
        if(ObjectUtils.isNotEmpty(vo.getStartDate())){
            //按时间范围选择
            String startTime= MyDateUtil.dateCheckOfDay(vo.getStartDate());
            String endTime= MyDateUtil.dateCheckOfDay(vo.getEndDate());
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  >= CONVERT(varchar(30),getdate() - "+startTime+",102)");
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  <= CONVERT(varchar(30),getdate() - "+endTime+",102)");
        }
        //统计有多少张
        List<ReportOrder> reportOrderList=list(queryWrapper);
        Set<String> reSet=new HashSet<>();
        for(ReportOrder re:reportOrderList){
            reSet.add(re.getOrderNum());
        }
        int totalAmount=reSet.size();
        IPage<ReportOrder> page=page(iPage,queryWrapper);
        return page.convert(reportOrder -> {
           ResponseCheckOfStuffVo responseCheckOfStuffVo=new ResponseCheckOfStuffVo();
           WorkOrder workOrder=workOrderService.queryByOrderNum(reportOrder.getOrderNum());
           ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
           ProcessInfo processInfo=processInfoService.getById(reportOrder.getReportProcess());
           if(ObjectUtils.isEmpty(workOrder.getNowProcess())||workOrder.getNowProcess()==0){
               responseCheckOfStuffVo.setNowProcess("该lot已完工");
           }else{
               responseCheckOfStuffVo.setNowProcess(processInfoService.getById(workOrder.getNowProcess()).getProcessName());
           }
           responseCheckOfStuffVo.setOrderNum(workOrder.getOrderNum());
           responseCheckOfStuffVo.setLotNo(parentOrder.getLotNo());
           responseCheckOfStuffVo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
           responseCheckOfStuffVo.setProcessName(processInfo.getProcessName());
           responseCheckOfStuffVo.setAcceptAmount(reportOrder.getBadAmount()+reportOrder.getReportAmount()+reportOrder.getMissingAmount());
           responseCheckOfStuffVo.setOverTime(reportOrder.getCreateTime());
           responseCheckOfStuffVo.setTotalAmount(totalAmount);
           return responseCheckOfStuffVo;
        });
    }

    @Override
    public IPage<ResponseCheckOfMachineVo> checkMachine(RequestCheckOfMachineVo vo) {
        IPage<ReportOrder> iPage=new Page<>(vo.getDisplayStart(),vo.getDisplayLength());
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        if(ObjectUtils.isNotEmpty(vo.getMachineNum())){
            queryWrapper.like("machine_num",vo.getMachineNum());
        }
        SysUser user=userService.getById(vo.getUserId());
        //判断管理员级别
        if(Objects.equals(user.getType(), "1")){
            //管理员条件查询
            if(StringUtils.isNotBlank(vo.getDeptName())){
                queryWrapper.eq("dept_id",vo.getDeptName());
            }
        } else if(Objects.equals(user.getType(), "0")||Objects.equals(user.getType(), "2")){//只能看自己部门的
            queryWrapper.eq("dept_id",user.getDeptId());
        }
        //时间范围
        if(ObjectUtils.isNotEmpty(vo.getStartDate())){
            //按时间范围选择
            String startTime= MyDateUtil.dateCheckOfDay(vo.getStartDate());
            String endTime= MyDateUtil.dateCheckOfDay(vo.getEndDate());
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  >= CONVERT(varchar(30),getdate() - "+startTime+",102)");
            queryWrapper.apply("CONVERT(varchar(30),create_time,102 )  <= CONVERT(varchar(30),getdate() - "+endTime+",102)");
        }
        //统计有多少张
        List<ReportOrder> reportOrderList=list(queryWrapper);
        Set<String> reSet=new HashSet<>();
        for(ReportOrder re:reportOrderList){
            reSet.add(re.getOrderNum());
        }
        int totalAmount=reSet.size();
        IPage<ReportOrder> page=page(iPage,queryWrapper);
        return page.convert(reportOrder -> {
            ResponseCheckOfMachineVo responseCheckOfMachineVo=new ResponseCheckOfMachineVo();
            WorkOrder workOrder=workOrderService.queryByOrderNum(reportOrder.getOrderNum());
            ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
            ProcessInfo processInfo=processInfoService.getById(reportOrder.getReportProcess());
            responseCheckOfMachineVo.setOrderNum(workOrder.getOrderNum());
            responseCheckOfMachineVo.setLotNo(parentOrder.getLotNo());
            responseCheckOfMachineVo.setPinName(pinLibraryService.getById(parentOrder.getPinId()).getPinName());
            responseCheckOfMachineVo.setProcessName(processInfo.getProcessName());
            responseCheckOfMachineVo.setAcceptAmount(reportOrder.getBadAmount()+reportOrder.getReportAmount()+reportOrder.getMissingAmount());
            responseCheckOfMachineVo.setCreateTime(reportOrder.getCreateTime());
            responseCheckOfMachineVo.setTotalAmount(totalAmount);
            return responseCheckOfMachineVo;
        });
    }

    @Override
    public void deleteReport(RequestDeleteReportInfoVo vo) {
        WorkOrder workOrder=workOrderService.getById(vo.getOrderId());
        //记录删除前的工序id和完结工序
        Integer beforeNow=workOrder.getNowProcess();
        Integer beforePast=workOrder.getPastProcess();
        Integer beforeNext=workOrder.getNextProcess();
        String beforeOver=workOrder.getOverProcess();
        //删除的哪道报工记录是否完结（针对分批次上报）
        boolean isOverOfDelete=true;
        int[] ids=MyStringUtil.toInt(workOrder.getProcess());
        //查询删除的上报记录
        QueryWrapper<ReportOrder> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",workOrder.getOrderNum());
        queryWrapper.eq("report_process",vo.getProcessId());
        List<ReportOrder> reportOrderList=list(queryWrapper);
        int amount=0;//删除后需要变更成的数量
        //删除的数量
        int badAmount=0;
        int supplyAmount=0;
        for(ReportOrder reportOrder:reportOrderList){
            if(reportOrder.isOver()) {
                //结束的上报记录才会统计
                badAmount += reportOrder.getBadAmount();
            }else {
                //未完结的上报记录
                supplyAmount += reportOrder.getSupplyAmount();
                badAmount=supplyAmount;
                isOverOfDelete=false;
            }
        }
        //找出删除工序的上一道工序
        int last = 0;
        for(int i=0;i<ids.length;i++){
            if(ids[i]==vo.getProcessId()){
                last=i-1;
            }
        }
        if(ids[0]==vo.getProcessId()||last<0){
            //删除第一道工序则归0
            amount=0;
        }else {
            //找出删除上报记录的上一道上报记录
            QueryWrapper<ReportOrder> lastQueryWrapper=new QueryWrapper<>();
            lastQueryWrapper.eq("order_num",workOrder.getOrderNum());
            lastQueryWrapper.eq("report_process",ids[last]);
            List<ReportOrder> lastReportOrderList=list(lastQueryWrapper);
            //统计删除上报记录的上一道上报记录值
            for(ReportOrder reportOrder:lastReportOrderList){
                //结束的上报记录才会统计
                if(reportOrder.isOver()) {
                    amount = amount + reportOrder.getReportAmount();
                }
            }
        }
        //如果是完结工序的上报记录，则需要改变工序
        if(isOverOfDelete){
            //工序变更
            int k=0;
            for(int i=0;i<ids.length;i++){
                //找到删除的上报记录的上报工序的id
                if(vo.getProcessId()==ids[i]){
                    k=i;
                }
            }
            workOrder.setNextProcess(beforeNow);
            workOrder.setNowProcess(beforePast);
            if(k-1<0){
                workOrder.setPastProcess(0);
            }else
                workOrder.setPastProcess(ids[k-1]);
            if(k==0){
                workOrder.setOverProcess("0");
            }else {
                String[] overProcess=beforeOver.split(",");
                String[] nowOverProcess=new String[overProcess.length-1];
                for(int i=0;i<nowOverProcess.length;i++){
                    nowOverProcess[i]=overProcess[i];
                }
                String over="0";
                for(String s:nowOverProcess){
                    over=MyStringUtil.intToString(Integer.parseInt(s),over);
                }
                workOrder.setOverProcess(over);
            }
            //保存一次
            workOrderService.updateById(workOrder);
        }
        //判断该工单是否本来是完结状态,如果完结父工单需要回溯
        if(Objects.equals(workOrder.getOrderStatus(), "2")){
            //改变状态
            workOrder.setOrderStatus("0");
            ParentOrder parentOrder=parentOrderService.getById(workOrder.getParentId());
            //减去数量
            parentOrder.setAmount(parentOrder.getAmount()-workOrder.getAmount());
            parentOrder.setBadAmount(parentOrder.getBadAmount()-workOrder.getBadAmount());
            parentOrderService.updateById(parentOrder);
        }
        //工单结算数量处理
        workOrder.setAmount(amount+workOrder.getSupplyAmount()-supplyAmount);
        workOrder.setBadAmount(workOrder.getBadAmount()-badAmount+supplyAmount);
        workOrder.setSupplyAmount(workOrder.getSupplyAmount()-supplyAmount);
        //保存,并执行删除上报记录操作
        workOrderService.updateById(workOrder);
        for(ReportOrder reportOrder:reportOrderList){
            //删除成功，记录删除记录
            if(removeById(reportOrder.getId())){
                deleteInfoService.addDeleteInfo(vo);
            }
        }
    }

    @Override
    public ResponseTodayDataVo getTodayData(String deptName) {
        ResponseTodayDataVo vo=new ResponseTodayDataVo();
        Integer deptId=deptService.queryByDeptName(deptName);
        //查询工序
        QueryWrapper<ProcessInfo> processQueryWrapper=new QueryWrapper<>();
        processQueryWrapper.eq("process_dept",deptId);
        List<ProcessInfo> processList=processInfoService.list(processQueryWrapper);
        String[] processNames=new String[processList.size()];
        Integer[] processIds=new Integer[processList.size()];
        for(int i=0;i<processList.size();i++){
            processNames[i]=processList.get(i).getProcessName();
            processIds[i]=processList.get(i).getId();
        }
        vo.setProcess(processNames);
        //查询所有在制工单,及其数量
        QueryWrapper<ParentOrder> parentQueryWrapper=new QueryWrapper<>();
        parentQueryWrapper.eq("order_dept",deptId);
        parentQueryWrapper.eq("is_over","0");
        List<ParentOrder> parentOrderList=parentOrderService.list(parentQueryWrapper);
        //定义工单号和数量
        String[] orders=new String[parentOrderList.size()];
        //用于统计在制
        Integer[] nowAmount=new Integer[parentOrderList.size()];
        Integer[] nowBad=new Integer[parentOrderList.size()];
        for(int i=0;i<parentOrderList.size();i++){
            orders[i]=parentOrderList.get(i).getLotNo();
            nowAmount[i]=parentOrderList.get(i).getAmount();
            nowBad[i]=parentOrderList.get(i).getBadAmount();
        }
        vo.setOrders(orders);
        vo.setAmount(nowAmount);
        vo.setBadAmount(nowBad);
        //查询所有在制今日上报数量
        Integer[] reportNums=new Integer[orders.length];
        for(int i=0;i<orders.length;i++){
            //只查询今天
            QueryWrapper<ReportOrder> reportQueryWrapper=new QueryWrapper<>();
            reportQueryWrapper.apply("CONVERT(varchar(30),create_time,102 ) = CONVERT(varchar(30),getdate(),102)");
            reportQueryWrapper.eq("dept_id",deptId);
            reportQueryWrapper.like("order_num",orders[i]);
            List<ReportOrder> reportOrderList=list(reportQueryWrapper);
            reportNums[i]=reportOrderList.size();
        }
        vo.setReportNums(reportNums);
        //查询每道工序流出数
        Integer[] putAmount=new Integer[processIds.length];
        for(int i=0;i<processIds.length;i++){
            //只查询今天
            QueryWrapper<ReportOrder> reportQueryWrapper=new QueryWrapper<>();
            reportQueryWrapper.apply("CONVERT(varchar(30),create_time,102 ) = CONVERT(varchar(30),getdate(),102)");
            reportQueryWrapper.eq("dept_id",deptId);
            reportQueryWrapper.eq("report_process",processIds[i]);
            List<ReportOrder> reportOrderList=list(reportQueryWrapper);
            putAmount[i]=reportOrderList.size();
        }
        vo.setPutAmount(putAmount);
        //查询各在制各站待产数量
        List<Integer[]> lotsList=new ArrayList<>();
        List<String[]> allOrderProcess=new ArrayList<>();
        //在制工单各站数量
        for(String orderNum:orders){
            ParentOrder parentOrder=parentOrderService.queryByLogNo(orderNum);
            int[] ids=MyStringUtil.toInt(parentOrder.getProcess());
            String[] orderProcess=new String[ids.length+2];
            for(int i=0;i<ids.length;i++){
                orderProcess[i]=processInfoService.getById(ids[i]).getProcessName();
            }
            orderProcess[orderProcess.length-1]="未检录";
            orderProcess[orderProcess.length-2]="已完工";
            //获取各站待产数量
            Integer[] lotNum=new Integer[orderProcess.length];
            for(int j=0;j<orderProcess.length;j++){
                if(j==orderProcess.length-2){//已完工的数据
                    QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("parent_id", parentOrder.getId());
                    queryWrapper.eq("now_process", 0);
                    queryWrapper.eq("is_check",true);
                    lotNum[j] = workOrderService.list(queryWrapper).size();
                }else if(j==orderProcess.length-1){//未检录数据
                    QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("parent_id", parentOrder.getId());
                    queryWrapper.eq("is_check",false);
                    lotNum[j] = workOrderService.list(queryWrapper).size();
                }else {
                    QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("parent_id", parentOrder.getId());
                    queryWrapper.eq("now_process", ids[j]);
                    queryWrapper.eq("is_check",true);
                    lotNum[j] = workOrderService.list(queryWrapper).size();
                }
            }
            lotsList.add(lotNum);
            allOrderProcess.add(orderProcess);
        }
        vo.setLots(lotsList);
        vo.setAllOrderProcess(allOrderProcess);
        return vo;
    }

}
